package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.printing.PrintJob;
	import flash.printing.PrintJobOptions;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import mylist.logs;
	
	/**
	 * ...
	 * @author db0@qq.com
	 */
	public class PrintBtn extends Sprite
	{
		public static var main:PrintBtn;
		private var printContainer:Sprite = new Sprite();
		public function PrintBtn()
		{
			if (main) return;
			main = this;
			visible = false;
			mouseChildren = false;
			buttonMode = true;
			addEventListener(Event.ADDED_TO_STAGE, init);
			
			addEventListener(MouseEvent.CLICK, printPage);
		}
		
		private function init(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			[Embed(source = "asset/print.png")]
			var Btn:Class;
			var bmp:Bitmap = new Btn();//打印图标
			addChild(bmp);
			bmp.x = stage.stageWidth - bmp.width*2;
			bmp.y = stage.stageHeight / 2 - bmp.height / 2;
		}
		
		public function makePrintContainer(bmp:Bitmap):void
		{
			while (printContainer.numChildren) 
			{
				var bmp:Bitmap = printContainer.getChildAt(printContainer.numChildren - 1) as Bitmap;
				printContainer.removeChild(bmp);
				//bmp.bitmapData.dispose();
			}
			printContainer.addChild(bmp);
			visible = true;
			stage.addChild(main);
		}
		
		public function hide():void
		{
			visible = false;
		}
		
		private function printPage(e:Event = null):void
		{
			var myPrintJob:PrintJob = new PrintJob();
			var options:PrintJobOptions = new PrintJobOptions();
			options.printAsBitmap = true;
			myPrintJob.start();
			
			try
			{
				if (myPrintJob.start())
				{
					myPrintJob.addPage(printContainer, null, options);
				}
			}
			catch (e:Error)
			{
				stage.addChild(new logs);
				logs.adds("Had problem adding the page to print job: " + e);
			}
			try
			{
				myPrintJob.send();
				visible = false;
			}
			catch (e:Error)
			{
				stage.addChild(new logs);
				logs.adds("Had problem printing: " + e);
			}
		}
	}
}
